package com.itheima.pinda.zuul.filter;

import cn.hutool.core.util.StrUtil;
import com.itheima.pinda.base.R;
import com.itheima.pinda.common.adapter.IgnoreTokenConfig;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import org.springframework.beans.factory.annotation.Value;

import javax.servlet.http.HttpServletRequest;



public abstract class BaseFilter extends ZuulFilter {

    @Value("{server.servlet.contex-path}")
    protected String zuulPrefix;

    protected boolean isIgnoreToken() {
        HttpServletRequest request = RequestContext.getCurrentContext().getRequest();
        String requestURI = request.getRequestURI();
        requestURI = StrUtil.subSuf(requestURI, zuulPrefix.length());
        requestURI = StrUtil.subSuf(requestURI, requestURI.indexOf("/", 1));
        boolean ignoreToken = IgnoreTokenConfig.isIgnoreToken(requestURI);
        return ignoreToken;
    }

    protected void errorResponse(String errMsg, int errCode, int httpStatusCode) {
        RequestContext currentContext = RequestContext.getCurrentContext();
        currentContext.setResponseStatusCode(httpStatusCode);
        currentContext.addZuulResponseHeader("Context-Type","application/json;charset=UTF-8");
        if(currentContext.getResponseBody() == null) {
            currentContext.setResponseBody(R.fail(errCode, errMsg).toString());
            currentContext.setSendZuulResponse(false);
        }
    }

}
